//post method= {post | put}
import { remote } from 'electron'
import BufferHelper  from 'bufferhelper'

/****
 *
 * @param options
 *     method: 'POST',
 *     protocol: 'https:',
 *     hostname: 'api.qdjxjy.com.cn',
 *     path: '/zjfore/exam/test/list',
 *     headers: {
 *       'Content-Type': 'application/json',
 *       'Authorization': 'Bearer ' + this.token
 *     }
 *
 *
 *
 * @param body 请求体
 * @returns {*}
 */
export function httpAction(options , body) {


  let bfh = new BufferHelper()
  let chunks = []
  let size = 0
  let isReturn=false;


  return new Promise((resolve, reject) => {

    const request = remote.net.request(options )

    request.on('response', (response) => {
      console.log(`**statusCode:${response.statusCode}`)

      response.on('data', (chunk) => {
        console.log(`ondata...`)
        console.log(chunk)
        console.log(chunk.length)

        size += chunk.length
        bfh.concat(chunk)
        if(chunk.length<4096){
          /***
           * 数据不多直接 返回
           */
          let responseBody = bfh.toBuffer().toString()
          isReturn=true;
          resolve(responseBody)


        }else{
          /***
           * 数据多 试一试 格式对直接返回 不对 等着
           */
          let responseBody = bfh.toBuffer().toString()
          try{
            let data = JSON.parse(responseBody)
            resolve(responseBody)
            isReturn=true;
          } catch(ee){
            isReturn=false;
          }
        }
      })
      response.on('end', () => {
        console.log('end')
        console.log(size)
        console.log(chunks.length)
        if(!isReturn){
          let responseBody = bfh.toBuffer().toString()
          console.log(responseBody) // data is incomplete
          resolve(responseBody)
        }
      })

      response.on('error', (error) => {
        console.log(`ERROR: ${JSON.stringify(error)}`)
        reject(error);
      })
    })

    // 写入数据
    request.write(body)
    // 结束请求
    request.end()

  })
}
